import { $msg } from './message'
/**
 * 订阅消息
 * @returns 
 */
export function $subscribeMsg(tmplIds) {
	if (!Array.isArray(tmplIds)) tmplIds = [tmplIds]
	return new Promise((resolve, reject) => {
		uni.requestSubscribeMessage({
			tmplIds,
			success: async res => {
				// if(res[tempId] === 'accept')
				//不管是否调用订阅，都可以买，这个地方还需要再优化
				resolve(res)
			},
			fail: err => reject(err)
		})
	})
}


/**
 * uni-app开发的APP端拉起小程序
 * path：指定小程序的页面路径
 */
export function $launchMiniProgram(WX_APP_ORGINAL_ID, path) {
	plus.share.getServices(shareList => {
		let shareWx = shareList.find(val => val.id == 'weixin')
		if (shareWx) {
			$msg('正在唤起小程序')
			//id是小程序原始ID而不是appid
			shareWx.launchMiniProgram({ id: WX_APP_ORGINAL_ID, path })
		} else
			$msg('未安装微信,无法打开小程序')

	}, e => $msg('唤起小程序失败'))
}

/**
 * 将网络图片转为base64
 * @param {*} img 
 * @returns 
 */
export function $parseImg2Base64(img) {
	return new Promise(((resolve, reject) => {
		uni.downloadFile({
			url: img,
			success(res) {
				uni.getFileSystemManager().readFile({
					filePath: res.tempFilePath, //选择图片返回的相对路径
					encoding: 'base64', //编码格式
					success: res => { //成功的回调
						resolve('data:image/png;base64,' + res.data)
					},
					fail: (e) => reject(e)
				})
			}
		})
	}))
}
